package com.sephiron.clocksynchronizer;

import java.util.ArrayList;
import java.util.UUID;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class CctvLab {
	private static final String TAG = "CctvLab";
	private static final String FILENAME = "cctvs.json";

	private ArrayList<Cctv> mCctvs;
	private CctvJSONSerializer mSerializer;

	private static CctvLab sCctvList;
	private Context mAppContext;

	private CctvLab(Context appContext) {
		mAppContext = appContext;
		mSerializer = new CctvJSONSerializer(mAppContext, FILENAME);

		try {
			mCctvs = mSerializer.loadCctvs();
		} catch (Exception e) {
			mCctvs = new ArrayList<Cctv>();
			Log.e(TAG, "Error loading cctv: ", e);
		}
	}

	public static CctvLab get(Context c) {
		if (sCctvList == null) {
			sCctvList = new CctvLab(c.getApplicationContext());
		}
		return sCctvList;
	}

	public void addCctv(Cctv c) {
		mCctvs.add(c);
	}

	public ArrayList<Cctv> getCctvs() {
		return mCctvs;
	}

	public Cctv getCctv(UUID id) {
		for (Cctv c : mCctvs) {
			if (c.getId().equals(id)) {
				return c;
			}
		}
		return null;
	}

	public boolean saveCctvs() {
		try {
			mSerializer.saveCctvs(mCctvs);
			Log.d(TAG, "cctvs saved to file");
			return true;
		} catch (Exception e) {
			Log.e(TAG, "Error saving cctvs", e);
			Toast.makeText(mAppContext, R.string.error_on_saving,
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}
	
	public void deleteCctv(Cctv c) {
		mCctvs.remove(c);
	}
}
